# coding:utf-8
from abc import ABC

from django.conf import settings
from django.core.cache import cache
from django.http import HttpResponse
from rest_framework import exceptions

from rest_framework.response import Response

from rest_framework.exceptions import AuthenticationFailed
from rest_framework.authentication import BaseAuthentication, BasicAuthentication
from teamup.models import User


class TeamUpTokenAuth(BaseAuthentication, ABC):

    def authenticate(self, request):
        authcode = request.META.get('HTTP_AUTHORIZATION', b'')
        auth = authcode.split()
        if not auth or auth[0].lower() != 'bearer' or len(auth)==1:
            raise exceptions.AuthenticationFailed('token invalid')
        token = auth[1]
        openid = check_token(token)

        if not openid:
            raise exceptions.AuthenticationFailed('token invalid')

        user = User.objects.filter(open_id=openid).first()
        if not user:
            raise exceptions.AuthenticationFailed('user not exist')

        return user, None


def check_token(token):
    t = cache.get(token)  # 2小时过期
    if t:
        return t
        # return True
    else:
        return None
        # return False
